package com.hyacinth.common.framework;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;

import com.hyacinth.common.constant.ThreadLocals;
import com.hyacinth.common.framework.i.IServiceSupport;
import com.hyacinth.common.jpql.SimpleJPQL;
import com.hyacinth.common.jpql.reserved.Comparation;

public abstract class ServiceSupport<D extends Domain> extends Generic<D> implements IServiceSupport<D>{
	
	public EntityManager manager() {
		return ThreadLocals.ENTITY_MANAGER.get();
	}
	
	@Override
	public void persist(D d) {
		d.persist();
	}
	
	@Override
	public void persist(Collection<D> ds) {
		for(D d : ds) {
			d.persist();
		}
	}
	
	@Override
	public void remove(D d) {
		d.remove();
	}
	
	@Override
	public void remove(Collection<D> ds) {
		for(D d : ds) {
			d.remove();
		}
	}
	
	@Override
	public void merge(D d) {
		d.meger();
	}
	
	@Override
	public void merge(Collection<D> ds) {
		for(D d : ds) {
			d.meger();
		}
	}
	
	@Override
	public D find(Long id) {
		return manager().find(parameter, id);
	}
	
	@Override
	public List<D> all() {
		SimpleJPQL jpql = new SimpleJPQL(parameter);
		jpql.where().add("deleted", Comparation.EQUAL, false);
		return jpql.multi(parameter);
	}
	
	@Override
	public void refresh(D d) {
		d.refresh();
	}

	@Override
	public void feignRemove(D d) {
		d.setDeleted(true);
		d.meger();
	}

	@Override
	public void feignRemove(Collection<D> ds) {
		for(D d : ds) {
			d.setDeleted(true);
			d.meger();
		}
	}
}
